package com.yanqu.road.server.manager.activity.summergames;

import com.yanqu.road.dao.impl.activity.summergames.CrossSummerGamesExchangeDataDaoImpl;
import com.yanqu.road.dao.impl.activity.summergames.CrossSummerGamesUserDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.summergames.cross.CrossSummerGamesExchangeData;
import com.yanqu.road.entity.activity.summergames.SummerGamesConfig;
import com.yanqu.road.entity.activity.summergames.cross.CrossSummerGamesUserData;
import com.yanqu.road.entity.activity.summergames.eApplyExchangeType;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.pb.activity.SummerGamesProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class CrossSummerGamesActivity {

    private ActivityInfo activityInfo;

    private Object lock = new Object();

    private SummerGamesConfig config;

    private AtomicLong exchangeId = new AtomicLong(0);

    /**
     * 是否取消了所有交换申请
     */
    private boolean endCancelAll = false;

    /**
     * 所有发布
     */
    private Map<Long, CrossSummerGamesExchangeData> allMap;

    /**
     * 玩家发布
     */
    private Map<Long, List<CrossSummerGamesExchangeData>> userPublishMap;

    /**
     * 商会发布
     */
    private Map<String, List<CrossSummerGamesExchangeData>> unionMap;

    /**
     * 玩家接收
     */
    private Map<Long, List<CrossSummerGamesExchangeData>> userReceiveMap;

    /**
     * 跨服发布
     */
    private Map<Long, CrossSummerGamesExchangeData> crossPublishMap;

    /**
     * 需要更新的数据
     */
    private LinkedList<CrossSummerGamesExchangeData> needUpdateList = new LinkedList<>();

    /**
     * 玩家数据
     */
    private Map<Long, CrossSummerGamesUserData> userDataMap;

    public CrossSummerGamesActivity(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }

    public void init() {
        initConfig();

        ConcurrentHashMap<Long, CrossSummerGamesExchangeData> crossPublishMapTemp = new ConcurrentHashMap<>();

        ConcurrentHashMap<Long, List<CrossSummerGamesExchangeData>> userReceiveMapTemp = new ConcurrentHashMap<>();

        ConcurrentHashMap<String, List<CrossSummerGamesExchangeData>> unionMapTemp = new ConcurrentHashMap<>();

        ConcurrentHashMap<Long, List<CrossSummerGamesExchangeData>> userPublishMapTemp = new ConcurrentHashMap<>();

        ConcurrentHashMap<Long, CrossSummerGamesExchangeData> allMapTemp = new ConcurrentHashMap<>();

        List<CrossSummerGamesExchangeData> dataList = new CrossSummerGamesExchangeDataDaoImpl().getCrossSummerGamesExchangeData(getActivityInfo().getActivityId());

        for (CrossSummerGamesExchangeData data : dataList) {
            //所有请求记录
            allMapTemp.put(data.getId(), data);
            if(data.getStatus() == 1){
                continue;
            }
            if(data.getStatus() == 0){
                //玩家发布
                if(!userPublishMapTemp.containsKey(data.getPUserId())){
                    userPublishMapTemp.put(data.getPUserId(), new LinkedList<>());
                }
                userPublishMapTemp.get(data.getPUserId()).add(data);

                if(!StringUtils.isNullOrEmpty(data.getUnionUid())){
                    //商会发布
                    if(!unionMapTemp.containsKey(data.getUnionUid())){
                        unionMapTemp.put(data.getUnionUid(), new LinkedList<>());
                    }
                    unionMapTemp.get(data.getUnionUid()).add(data);
                }else if(data.getAUserId() > 0){
                    //指定接收
                    if(!userReceiveMapTemp.containsKey(data.getAUserId())){
                        userReceiveMapTemp.put(data.getAUserId(), new LinkedList<>());
                    }
                    userReceiveMapTemp.get(data.getAUserId()).add(data);
                }else {
                    //跨服发布
                    crossPublishMapTemp.put(data.getId(), data);
                }
            }
        }

        exchangeId = new AtomicLong(new CrossSummerGamesExchangeDataDaoImpl().getMaxExchangeId(activityInfo.getActivityId()));

        userDataMap = new CrossSummerGamesUserDataDaoImpl().getCrossSummerGamesUserData(getActivityInfo().getActivityId());

        crossPublishMap = crossPublishMapTemp;

        userReceiveMap = userReceiveMapTemp;

        unionMap = unionMapTemp;

        userPublishMap = userPublishMapTemp;

        allMap = allMapTemp;
    }

    public void initConfig(){

        SummerGamesConfig temp = new SummerGamesConfig(this.activityInfo);

        List<Integer> activityIdList = new ArrayList<>();
        activityIdList.add(activityInfo.getActivityId());
        Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(activityIdList).get(activityInfo.getActivityId());

        temp.setSUMMERGAME_EXCHANGE_RECORD_CROSS(activityConfigMap.get(eActivityConfigType.SUMMERGAME_EXCHANGE_RECORD_CROSS.getName()).getIntValue());
//        temp.setSUMMERGAME_EXCHANGE_RECORD_BASE(activityConfigMap.get(eActivityConfigType.SUMMERGAME_EXCHANGE_RECORD_BASE.getName()).getIntValue());
        temp.setSUMMERGAME_PUBLISH_EXCHANGE_RECORD(activityConfigMap.get(eActivityConfigType.SUMMERGAME_PUBLISH_EXCHANGE_RECORD.getName()).getIntValue());
        temp.setSUMMERGAME_RECEIVE_EXCHANGE_RECORD(activityConfigMap.get(eActivityConfigType.SUMMERGAME_RECEIVE_EXCHANGE_RECORD.getName()).getIntValue());

        config = temp;
    }

    public ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public void save(){

        if(needUpdateList.size() > 0){
            List<CrossSummerGamesExchangeData> list;
            synchronized (needUpdateList){
                list = new ArrayList<>(needUpdateList);
                needUpdateList.clear();
            }
            for (CrossSummerGamesExchangeData data : list) {
                if(data.isInsertOption()){
                    new CrossSummerGamesExchangeDataDaoImpl().add(data);
                }else if(data.isUpdateOption()){
                    new CrossSummerGamesExchangeDataDaoImpl().update(data);
                }
            }
        }

        for (Map.Entry<Long, CrossSummerGamesUserData> entry : userDataMap.entrySet()) {
            CrossSummerGamesUserData data = entry.getValue();
            if(data.isInsertOption()){
                new CrossSummerGamesUserDataDaoImpl().add(data);
            }else if(data.isUpdateOption()){
                new CrossSummerGamesUserDataDaoImpl().update(data);
            }
        }
    }

    /**
     * 预发布
     * @param appointUserId 指定玩家
     * @param appointUserServerId
     * @param union 商会
     * @param nickName
     */
    public void applyExchange(long serverId, long playerId, int wantId, int payId, long appointUserId, long appointUserServerId, String union, String nickName) {

        CrossSummerGamesExchangeData exchangeData = initExchangeData(serverId, playerId, wantId, payId);
        exchangeData.setNickName(nickName);
        exchangeData.setPServerId(serverId);
        if(appointUserId > 0){

            CrossSummerGamesUserData appUserData = getUserData(appointUserId);
            if(appUserData.getReceiveSet() == 1){
                sendApplyErrorResp(serverId, playerId, payId, exchangeData, GameErrorCode.E_SUMMER_GAMES_NOT_ACCEPT_APPOINT);
                return;
            }

            exchangeData.setAServerId(appointUserServerId);
            exchangeData.setAUserId(appointUserId);
            exchangeData.setApplyType(eApplyExchangeType.Appointed.getType());

        }else if(!StringUtils.isNullOrEmpty(union)){

            exchangeData.setUnionUid(union);
            exchangeData.setApplyType(eApplyExchangeType.Union.getType());

        }else {
            exchangeData.setApplyType(eApplyExchangeType.Default.getType());
        }

        //判断上限
        if(appointUserId <= 0){
            synchronized (lock){
                int totalPublish = 0;
                List<CrossSummerGamesExchangeData> publishList = getUserPublishList(playerId);
                if(!publishList.isEmpty()) {
                    if (StringUtils.isNullOrEmpty(union)) {
                        for (int i = 0; i < publishList.size(); i++) {
                            CrossSummerGamesExchangeData data = publishList.get(i);
                            if(data.getApplyType() == eApplyExchangeType.Default.getType() && data.getStatus() == 0){
                                totalPublish++;
                            }
                        }
                    } else {
                        for (int i = 0; i < publishList.size(); i++) {
                            CrossSummerGamesExchangeData data = publishList.get(i);
                            if(data.getApplyType() == eApplyExchangeType.Union.getType() && data.getStatus() == 0){
                                totalPublish++;
                            }
                        }
                    }
                }
                if(totalPublish >= config.getSUMMERGAME_PUBLISH_EXCHANGE_RECORD()){
                    sendApplyErrorResp(serverId, playerId, payId, exchangeData, GameErrorCode.E_SUMMER_GAMES_PUBLISH_TIMES_LIMIT);
                    return;
                }

                //设定id
                exchangeData.setId(exchangeId.incrementAndGet());
                //玩家发布
                addUserApply(exchangeData);
            }
        }else {
            //判读接收上限
            synchronized (lock){

                List<CrossSummerGamesExchangeData> dataList = userReceiveMap.getOrDefault(exchangeData.getAUserId(), Collections.emptyList());
                if(dataList.size() >= config.getSUMMERGAME_RECEIVE_EXCHANGE_RECORD()) {
                    sendApplyErrorResp(serverId, playerId, payId, exchangeData, GameErrorCode.E_SUMMER_GAMES_RECEIVE_TIMES_LIMIT);
                    return;
                }
                //设定id
                exchangeData.setId(exchangeId.incrementAndGet());
                //玩家发布
                addUserApply(exchangeData);
                //
                addUserReceive(exchangeData);
            }
        }

        //所有发布
        allMap.put(exchangeData.getId(), exchangeData);

        //更新
        addNeedUpdate(exchangeData);

        SummerGamesProto.CrossSummerGamesApplyExchangeCheckRespMsg.Builder serverMsg = SummerGamesProto.CrossSummerGamesApplyExchangeCheckRespMsg.newBuilder();
        serverMsg.setApplyId(exchangeData.getId());
        serverMsg.setPayId(payId);
        serverMsg.setActivityId(getActivityInfo().getActivityId());
        serverMsg.setRet(0);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_EXCHANGE_APPLY_CHECK_FROM_CROSS, serverMsg));
    }

    private void sendApplyErrorResp(long serverId, long playerId, int payId, CrossSummerGamesExchangeData exchangeData, short eSummerGamesPublishTimesLimit) {
        SummerGamesProto.CrossSummerGamesApplyExchangeCheckRespMsg.Builder serverMsg = SummerGamesProto.CrossSummerGamesApplyExchangeCheckRespMsg.newBuilder();
        serverMsg.setApplyId(exchangeData.getId());
        serverMsg.setPayId(payId);
        serverMsg.setActivityId(getActivityInfo().getActivityId());
        serverMsg.setRet(eSummerGamesPublishTimesLimit);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_EXCHANGE_APPLY_CHECK_FROM_CROSS, serverMsg));
    }

    /**
     * 正式发布
     */
    public void applyExchangeConfirm(long serverId, long playerId, long applyId){

        CrossSummerGamesExchangeData exchangeData = allMap.get(applyId);
        if(exchangeData == null){
            //失败了
            CrossSummerGamesMgr.getLogger().error("玩家{}，提交申请{}，确认失败", playerId, applyId);
            return;
        }

        exchangeData.setStatus(0);
        exchangeData.setLastUpdateTime(System.currentTimeMillis());
        if(exchangeData.getAUserId() > 0){

            //指定玩家接收
            addUserReceive(exchangeData);

        }else if(!StringUtils.isNullOrEmpty(exchangeData.getUnionUid())){

            //商会接收
            addUnionApply(exchangeData);

        }else {

            //跨服发布
            crossPublishMap.put(exchangeData.getId(), exchangeData);
        }

        //更新
        addNeedUpdate(exchangeData);

        SummerGamesProto.CrossSummerGamesApplyExchangeRespMsg.Builder serverMsg = SummerGamesProto.CrossSummerGamesApplyExchangeRespMsg.newBuilder();
        serverMsg.setActivityId(getActivityInfo().getActivityId());
        serverMsg.setRet(0);
        SummerGamesProto.SummerGamesExchangeInfoTemp.Builder builder = getExchangeBuilder(exchangeData);
        serverMsg.setInfo(builder);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_EXCHANGE_APPLY_FROM_CROSS, serverMsg));

        //通知
        if(exchangeData.getAUserId() > 0){
            syncUserList(exchangeData.getAServerId(), exchangeData.getAUserId(), 1);
        }else if(!StringUtils.isNullOrEmpty(exchangeData.getUnionUid())){

        }

    }

    /**
     * 交换大厅
     */
    public void exchangeList(long serverId, long playerId, SummerGamesProto.CrossSummerGamesExchangeListReqMsg reqMsg) {

        String unionUid = reqMsg.getUnionUid();
        long userId = reqMsg.getUserId();
        int type = reqMsg.getType();
        int pageNum = reqMsg.getPageNum();
        List<Integer> needMedalsList = reqMsg.getMedalsList();
        List<Integer> ownList = reqMsg.getOwnMedalsList();

        SummerGamesProto.SummerGamesExchangeListRespMsg.Builder clientMsg = SummerGamesProto.SummerGamesExchangeListRespMsg.newBuilder();
        clientMsg.setRet(0);
        clientMsg.setPageNum(pageNum);

        if(userId > 0 || type == 2){

            List<CrossSummerGamesExchangeData> dataList = userPublishMap.get(playerId);
            if(dataList != null){
                for (int i = 0; i < dataList.size(); i++) {
                    CrossSummerGamesExchangeData exchangeData = dataList.get(i);
                    if(exchangeData.getStatus() != 0){
                        continue;
                    }
                    if(exchangeData.getAUserId() <= 0){
                        continue;
                    }
                    if (exchangeData.getPUserId() == playerId){
                        continue;
                    }
                    clientMsg.addList(getExchangeBuilder(exchangeData));
                }
            }

        }else if(!StringUtils.isNullOrEmpty(unionUid)){
            //商会不过滤
            List<CrossSummerGamesExchangeData> dataList = unionMap.get(unionUid);
            if(dataList != null) {
                List<CrossSummerGamesExchangeData> resultList = new ArrayList<>();
                for (int i = 0; i < dataList.size(); i++) {
                    CrossSummerGamesExchangeData exchangeData = dataList.get(i);
                    if (exchangeData.getStatus() != 0) {
                        continue;
                    }
                    if (exchangeData.getPUserId() == playerId){
                        continue;
                    }
                    if (!needMedalsList.isEmpty() && !needMedalsList.contains(exchangeData.getPGoodsId())) {
                        continue;
                    }
                    resultList.add(exchangeData);
                }
                //排序
                resultList.sort(new SummerGamesExchangeSort(ownList));
                for (CrossSummerGamesExchangeData exchangeData : resultList) {
                    clientMsg.addList(getExchangeBuilder(exchangeData));
                }
            }

        }else {

            if(needMedalsList.isEmpty()){

                //不过滤，随机50个
                List<Long> keyList = new ArrayList<>(crossPublishMap.keySet());
                Random random = new Random();
                List<Long> randomKeyList = new ArrayList<>();
                for (int i = 0; i < 100 && keyList.size() > 0; i++) {
                    int idx = random.nextInt(keyList.size());
                    randomKeyList.add(keyList.remove(idx));
                }
                int add = 0;
                List<CrossSummerGamesExchangeData> resultList = new ArrayList<>();
                for (int i = 0; i < randomKeyList.size(); i++) {
                    Long key = randomKeyList.get(i);
                    CrossSummerGamesExchangeData data = crossPublishMap.get(key);
                    if(data == null || data.getStatus() != 0){
                        continue;
                    }
                    if (data.getPUserId() == playerId){
                        continue;
                    }
                    add++;
                    resultList.add(data);
                    if(add >= 50){
                        break;
                    }
                }

                //排序
                resultList.sort(new SummerGamesExchangeSort(ownList));
                for (CrossSummerGamesExchangeData exchangeData : resultList) {
                    clientMsg.addList(getExchangeBuilder(exchangeData));
                }

            }else {

                //过滤，满足条件最多2000个来随机
                List<CrossSummerGamesExchangeData> dataList = new ArrayList<>();
                int count = 0;
                for (Map.Entry<Long, CrossSummerGamesExchangeData> entry : crossPublishMap.entrySet()) {
                    CrossSummerGamesExchangeData data = entry.getValue();
                    if(data.getStatus() != 0){
                        continue;
                    }
                    if(!needMedalsList.contains(data.getPGoodsId())){
                        continue;
                    }
                    if (data.getPUserId() == playerId){
                        continue;
                    }
                    count++;

                    dataList.add(data);
                    if(count >= 2000){
                        break;
                    }
                }
                //排序
                dataList.sort(new SummerGamesExchangeSort(ownList));

                //取当前页数据
                int pageSize = 50;
                int startIndex = (pageNum - 1) * pageSize;
                if(startIndex >= dataList.size()){
                    pageNum = 1;
                    startIndex = 0;
                    clientMsg.setPageNum(pageNum);
                }
                startIndex = Math.max(0, startIndex);

                for (int i = startIndex; i < startIndex + pageSize && i < dataList.size(); i++) {
                    CrossSummerGamesExchangeData data = dataList.get(i);
                    clientMsg.addList(getExchangeBuilder(data));
                }
            }
        }

        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_EXCHANGE_LIST, clientMsg));
    }

    /**
     * 同意交换
     */
    public SummerGamesProto.CrossSummerGamesExchangeAgreeRespMsg.Builder agreeExchange(long serverId, long playerId, String unionUid, long applyId, int medalsId) {

        SummerGamesProto.CrossSummerGamesExchangeAgreeRespMsg.Builder serverMsg = SummerGamesProto.CrossSummerGamesExchangeAgreeRespMsg.newBuilder();
        serverMsg.setRet(0);
        serverMsg.setMedalsId(medalsId);
        CrossSummerGamesExchangeData exchangeData = allMap.get(applyId);
        if(exchangeData == null || medalsId != exchangeData.getWantGoodsId()){
            serverMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            return serverMsg;
        }

        synchronized (lock) {
            if (exchangeData.getStatus() != 0) {
                serverMsg.setRet(GameErrorCode.E_SUMMER_GAMES_EXCHANGE_INFO_OUT_TIME);
                return serverMsg;
            }
            //不是自己发布的
            if (exchangeData.getPUserId() == playerId){
                serverMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
                return serverMsg;
            }

            //不是指定的人
            if(exchangeData.getAUserId() > 0 && exchangeData.getAUserId() != playerId){
                serverMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
                return serverMsg;
            }
            //不是商会
            if(!StringUtils.isNullOrEmpty(exchangeData.getUnionUid())){
                if(!Objects.equals(exchangeData.getUnionUid(), unionUid)){
                    serverMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
                    return serverMsg;
                }
            }
            exchangeData.setStatus(1);
            if(exchangeData.getAServerId() <= 0){
                exchangeData.setAServerId(serverId);
            }
            if(exchangeData.getAUserId() <= 0){
                exchangeData.setAUserId(playerId);
            }
            exchangeData.setLastUpdateTime(System.currentTimeMillis());
        }

        addNeedUpdate(exchangeData);

        if(exchangeData.getApplyType() == 2){
            //清除个人接收列表
            removeUserReceive(exchangeData.getAUserId(), applyId);

        }else if(!StringUtils.isNullOrEmpty(exchangeData.getUnionUid())){
            //清除商会申请
            removeUnionApply(exchangeData.getUnionUid(), applyId);

        }else {

            //清除跨服申请
            crossPublishMap.remove(applyId);
        }

        //通知申请人，来领取奖励邮件
        SummerGamesProto.CrossSummerGamesExchangeDoneNotifyMsg.Builder notify = SummerGamesProto.CrossSummerGamesExchangeDoneNotifyMsg.newBuilder();
        notify.setActivityId(getActivityInfo().getActivityId());
        notify.setUserId(exchangeData.getPUserId());
        notify.setId(exchangeData.getId());
        MessageHelper.sendPacket(exchangeData.getPServerId(), exchangeData.getPUserId(), YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_EXCHANGE_DONE_NOTIFY_FROM_CROSS, notify));

        //清除发布者列表
        removeUserApply(exchangeData.getPUserId(), applyId);

        //同步申请者列表
        syncUserList(exchangeData.getPServerId(), exchangeData.getPUserId(), 0);

        serverMsg.setInfo(getExchangeBuilder(exchangeData));
        return serverMsg;
    }

    private void syncUserList(long serverId, long userId, int type) {
        //下发发布者列表
        SummerGamesProto.SummerGamesMyListNotifyMsg.Builder notifyUser = SummerGamesProto.SummerGamesMyListNotifyMsg.newBuilder();
        notifyUser.setType(type);
        if(type == 0) {
            List<CrossSummerGamesExchangeData> dataList = userPublishMap.get(userId);
            if (dataList != null) {
                for (int i = 0; i < dataList.size(); i++) {
                    CrossSummerGamesExchangeData temp = dataList.get(i);
                    if (temp.getStatus() == 0) {
                        notifyUser.addExchange(getExchangeBuilder(temp));
                    }
                }
            }
        }else {
            List<CrossSummerGamesExchangeData> dataList = userReceiveMap.get(userId);
            if(dataList != null){
                for (int i = 0; i < dataList.size(); i++) {
                    CrossSummerGamesExchangeData exchangeData = dataList.get(i);
                    if(exchangeData.getStatus() == 0){
                        notifyUser.addExchange(getExchangeBuilder(exchangeData));
                    }
                }
            }
        }
        MessageHelper.sendPacket(serverId, userId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_EXCHANGE_MY_SYNC, notifyUser));
    }

    /**
     * 我的列表
     * @param type 0：我发布， 1：我接收
     */
    public void myExchangeList(long serverId, long playerId, int type) {

        SummerGamesProto.SummerGamesExchangeMyListRespMsg.Builder clientMsg = SummerGamesProto.SummerGamesExchangeMyListRespMsg.newBuilder();
        clientMsg.setRet(0);

        if(type == 0){

            List<CrossSummerGamesExchangeData> dataList = userPublishMap.get(playerId);
            if(dataList != null){
                for (int i = 0; i < dataList.size(); i++) {
                    CrossSummerGamesExchangeData exchangeData = dataList.get(i);
                    if(exchangeData.getStatus() == 0){
                        clientMsg.addExchange(getExchangeBuilder(exchangeData));
                    }
                }
            }

        }else if(type == 1){
            List<CrossSummerGamesExchangeData> dataList = userReceiveMap.get(playerId);
            if(dataList != null){
                for (int i = 0; i < dataList.size(); i++) {
                    CrossSummerGamesExchangeData exchangeData = dataList.get(i);
                    if(exchangeData.getStatus() == 0){
                        clientMsg.addExchange(getExchangeBuilder(exchangeData));
                    }
                }
            }
        }

        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_EXCHANGE_MY, clientMsg));

    }

    /**
     * 申请人获得奖杯
     */
    public void getExchangeReward(long serverId, long playerId, long applyId) {
        SummerGamesProto.CrossSummerGamesExchangeDoneRewardBackMsg.Builder builder = SummerGamesProto.CrossSummerGamesExchangeDoneRewardBackMsg.newBuilder();
        builder.setRet(0);

        CrossSummerGamesExchangeData exchangeData = allMap.get(applyId);
        if(exchangeData == null){
            return;
        }
        synchronized (lock){
            if(exchangeData.getStatus() != 1){
                return;
            }
            exchangeData.setStatus(3);
            exchangeData.setLastUpdateTime(System.currentTimeMillis());
        }
        addNeedUpdate(exchangeData);

        SummerGamesProto.SummerGamesExchangeInfoTemp.Builder exchangeBuilder = getExchangeBuilder(exchangeData);
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(exchangeData.getPUserId());
        if(userBaseInfo != null) {
            exchangeBuilder.setTempUserName(userBaseInfo.getNickName());
        }

        builder.setInfo(exchangeBuilder);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_EXCHANGE_DONE_REWARD_FROM_CROSS, builder));
    }

    public void receiveSet(long serverId, long playerId, int type) {

        CrossSummerGamesUserData userData = getUserData(playerId);
        userData.setReceiveSet(type);

        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_RECEIVE_SETTING, SummerGamesProto.SummerGamesReceiveSettingRespMsg.newBuilder().setRet(0).setReceiveSet(type)));
    }

    public CrossSummerGamesUserData getUserDataIfNull(long playerId) {
        return userDataMap.get(playerId);
    }

    public CrossSummerGamesUserData getUserData(long playerId) {
        CrossSummerGamesUserData userData = userDataMap.get(playerId);
        if(userData == null){
            synchronized (userDataMap){
                userData = userDataMap.get(playerId);
                if(userData == null){
                    userData = new CrossSummerGamesUserData();
                    userData.setInsertOption();
                    userData.setActivityId(getActivityInfo().getActivityId());
                    userData.setUserId(playerId);
                    userDataMap.put(playerId, userData);
                }
            }
        }
        return userData;
    }

    /**
     * 取消申请
     */
    public void cancelApply(long serverId, long playerId, long applyId) {

        CrossSummerGamesExchangeData exchangeData = allMap.get(applyId);
        if(exchangeData == null){
            SummerGamesProto.SummerGamesCancelExchangeRespMsg.Builder clientMsg = SummerGamesProto.SummerGamesCancelExchangeRespMsg.newBuilder();
            clientMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_EXCHANGE_CANCEL, clientMsg));
            return;
        }

        boolean success = true;
        synchronized (lock){
            if(exchangeData.getStatus() != 0){
                success = false;
            }else {
                exchangeData.setStatus(4);
                exchangeData.setLastUpdateTime(System.currentTimeMillis());
            }
        }

        if(!success){
            SummerGamesProto.SummerGamesCancelExchangeRespMsg.Builder clientMsg = SummerGamesProto.SummerGamesCancelExchangeRespMsg.newBuilder();
            clientMsg.setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR);
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_EXCHANGE_CANCEL, clientMsg));
            return;
        }

        addNeedUpdate(exchangeData);

        removeUserApply(playerId, applyId);

        if(exchangeData.getApplyType() == eApplyExchangeType.Default.getType()){
            crossPublishMap.remove(exchangeData.getId());
        }else if(exchangeData.getApplyType() == eApplyExchangeType.Union.getType()){
            removeUnionApply(exchangeData.getUnionUid(), exchangeData.getId());
        }else {
            removeUserReceive(exchangeData.getAUserId(), exchangeData.getId());
        }

        SummerGamesProto.SummerGamesCancelExchangeRespMsg.Builder serverMsg = SummerGamesProto.SummerGamesCancelExchangeRespMsg.newBuilder();
        serverMsg.setRet(0);
        serverMsg.setInfo(getExchangeBuilder(exchangeData));
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_EXCHANGE_CANCEL_FROM_CROSS, serverMsg));

        syncUserList(serverId, playerId, 0);
    }

    public void useLogin(long serverId, long playerId, SummerGamesProto.SummerGamesUserDataSyncMsg msg) {

        CrossSummerGamesUserData userDataIfNull = getUserDataIfNull(playerId);

        SummerGamesProto.SummerGamesUserMainDataTemp.Builder builder = msg.getUserData().toBuilder();

        if(userDataIfNull != null){
            builder.setReceiveSet(userDataIfNull.getReceiveSet());
        }
        SummerGamesProto.SummerGamesUserDataSyncMsg.Builder clientMsg = SummerGamesProto.SummerGamesUserDataSyncMsg.newBuilder();
        clientMsg.setUserData(builder);

        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_USER_SYNC, clientMsg));
    }

    /**
     * 拒绝请求
     */
    public void refuseApply(long serverId, long playerId, long applyId) {

        List<CrossSummerGamesExchangeData> dataList = userReceiveMap.get(playerId);
        if(dataList == null || dataList.size() == 0){
            MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_REFUSE_APPLY, SummerGamesProto.SummerGamesRefuseApplyRespMsg.newBuilder().setRet(0)));
            syncUserList(serverId, playerId, 1);
            return;
        }

        Map<Long, Long> changUserList = new HashMap<>();
        List<CrossSummerGamesExchangeData> changeDataList = new ArrayList<>();
        synchronized (lock){

            if(applyId > 0){

                CrossSummerGamesExchangeData data = allMap.get(applyId);
                if(data == null){
                    MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_REFUSE_APPLY,
                            SummerGamesProto.SummerGamesRefuseApplyRespMsg.newBuilder().setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR)));
                    return;
                }

                if(data.getStatus() != 0){
                    MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_REFUSE_APPLY,
                            SummerGamesProto.SummerGamesRefuseApplyRespMsg.newBuilder().setRet(GameErrorCode.E_SUMMER_GAMES_EXCHANGE_INFO_OUT_TIME)));
                    return;
                }

                if(data.getAUserId() != playerId){
                    MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_SUMMER_GAMES_REFUSE_APPLY,
                            SummerGamesProto.SummerGamesRefuseApplyRespMsg.newBuilder().setRet(GameErrorCode.E_REQUEST_ARGUMENT_ERROR)));
                    return;
                }

                data.setStatus(5);
                data.setLastUpdateTime(System.currentTimeMillis());
                changUserList.put(data.getPUserId(), data.getPServerId());

                changeDataList.add(data);

                addNeedUpdate(data);

            }else {

                dataList = userReceiveMap.get(playerId);
                if(dataList == null || dataList.size() == 0){
                    return;
                }

                for (int i = 0; i < dataList.size(); i++) {
                    CrossSummerGamesExchangeData data = dataList.get(i);
                    if(data.getStatus() != 0){
                        continue;
                    }
                    data.setStatus(5);

                    addNeedUpdate(data);

                    changUserList.put(data.getPUserId(), data.getPServerId());
                    changeDataList.add(data);
                }
            }
        }

        if(applyId > 0){
            removeUserReceive(playerId, applyId);
        }else {
            userReceiveMap.remove(playerId);
        }

        for (CrossSummerGamesExchangeData data : changeDataList) {
            //移除个人发布
            removeUserApply(data.getPUserId(), data.getId());

            if(data.getApplyType() == eApplyExchangeType.Default.getType()){
                //移除跨服发布  缓存
                crossPublishMap.remove(data.getId());
            }else if(!StringUtils.isNullOrEmpty(data.getUnionUid())){
                //移除商会发布  缓存
                removeUnionApply(data.getUnionUid(), data.getId());
            }
        }

        SummerGamesProto.CrossSummerGamesRefuseApplyRespMsg.Builder serverMsg = SummerGamesProto.CrossSummerGamesRefuseApplyRespMsg.newBuilder();
        serverMsg.setRet(0);
        serverMsg.setActivityId(activityInfo.getActivityId());
        for (CrossSummerGamesExchangeData data : changeDataList) {
            serverMsg.addInfo(getExchangeBuilder(data));
        }
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_EXCHANGE_REFUSE_FROM_CROSS, serverMsg));

        //同步自身的接受列表
        syncUserList(serverId, playerId, 1);

        Map<Long, SummerGamesProto.CrossSummerGamesRefuseNotifyMsg.Builder> msgMap = new HashMap<>();
        for (CrossSummerGamesExchangeData data : changeDataList) {
            if(!msgMap.containsKey(data.getPUserId())){
                msgMap.put(data.getPUserId(), SummerGamesProto.CrossSummerGamesRefuseNotifyMsg.newBuilder());
            }
            msgMap.get(data.getPUserId()).addInfo(getExchangeBuilder(data));
        }

        for (Map.Entry<Long, SummerGamesProto.CrossSummerGamesRefuseNotifyMsg.Builder> entry : msgMap.entrySet()) {
            SummerGamesProto.CrossSummerGamesRefuseNotifyMsg.Builder notifyMsg = entry.getValue();
            //返还道具
            MessageHelper.sendPacket(changUserList.get(entry.getKey()), entry.getKey(), YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_EXCHANGE_REFUSE_NOTIFY_FROM_CROSS, notifyMsg));
        }

        //同步玩家的最新列表
        for (Map.Entry<Long, Long> entry : changUserList.entrySet()) {
            syncUserList(entry.getValue(), entry.getKey(), 0);
        }
    }

    /**
     * 活动过期取消所有申请，返还奖杯子
     */
    public void cancelApplyInTimeOut(){
        long now = System.currentTimeMillis() / 1000;
        if(now < activityInfo.getEndShowTime() + 5 * DateHelper.MINUTE_SECONDS){
            return;
        }
        if(endCancelAll){
            return;
        }
        endCancelAll = true;
        CrossSummerGamesMgr.getLogger().info("活动结束，开始取消所有交换申请");
        Map<Long, Long> userServerMap = new HashMap<>();
        Map<Long, Property> userRewardMap = new HashMap<>();
        synchronized (lock){

            //取消商会发布
            List<String> keyList = new ArrayList<>(unionMap.keySet());
            for (String unionUid : keyList) {
                List<CrossSummerGamesExchangeData> dataList = unionMap.remove(unionUid);
                if(dataList == null || dataList.isEmpty()){
                    continue;
                }
                for (CrossSummerGamesExchangeData data : dataList) {
                    if(data.getStatus() != 0){
                        continue;
                    }
                    data.setStatus(4);
                    userServerMap.put(data.getPUserId(), data.getPServerId());
                    if(!userRewardMap.containsKey(data.getPUserId())){
                        userRewardMap.put(data.getPUserId(), new Property());
                    }
                    userRewardMap.get(data.getPUserId()).addProperty(data.getPGoodsId(), BigInteger.ONE);

                    addNeedUpdate(data);
                }
            }

            //跨服取消
            for (Map.Entry<Long, CrossSummerGamesExchangeData> entry : crossPublishMap.entrySet()) {
                CrossSummerGamesExchangeData data = entry.getValue();
                if(data.getStatus() != 0){
                    continue;
                }
                data.setStatus(4);
                userServerMap.put(data.getPUserId(), data.getPServerId());
                if(!userRewardMap.containsKey(data.getPUserId())){
                    userRewardMap.put(data.getPUserId(), new Property());
                }
                userRewardMap.get(data.getPUserId()).addProperty(data.getPGoodsId(), BigInteger.ONE);
                addNeedUpdate(data);
            }

            //指定
            //取消商会发布
            List<Long> receiveKeyList = new ArrayList<>(userReceiveMap.keySet());
            for (Long uid : receiveKeyList) {
                List<CrossSummerGamesExchangeData> dataList = userReceiveMap.remove(uid);
                if(dataList == null || dataList.isEmpty()){
                    continue;
                }
                for (CrossSummerGamesExchangeData data : dataList) {
                    if(data.getStatus() != 0){
                        continue;
                    }
                    data.setStatus(4);
                    userServerMap.put(data.getPUserId(), data.getPServerId());
                    if(!userRewardMap.containsKey(data.getPUserId())){
                        userRewardMap.put(data.getPUserId(), new Property());
                    }
                    userRewardMap.get(data.getPUserId()).addProperty(data.getPGoodsId(), BigInteger.ONE);
                    if(data.getAUserId() > 0){
                        removeUserReceive(data.getAUserId(), data.getId());
                    }
                    addNeedUpdate(data);
                }
            }

            crossPublishMap.clear();
        }

        if(userRewardMap.isEmpty()){
            return;
        }

        for (Map.Entry<Long, Property> entry : userRewardMap.entrySet()) {
            Long userId = entry.getKey();

            SummerGamesProto.CrossSummerGamesAutoCancelApplySync.Builder sync = SummerGamesProto.CrossSummerGamesAutoCancelApplySync.newBuilder();
            sync.setUserId(userId);
            sync.setReward(PropertyHelper.parsePropertyToString(userRewardMap.get(userId)));

            MessageHelper.sendPacket(userServerMap.get(userId), userId, YanQuMessageUtils.buildMessage(Protocol.S_SUMMER_GAMES_AUTO_CANCEL_APPLY, sync));
        }
    }

    public void addNeedUpdate(CrossSummerGamesExchangeData exchangeData) {
        synchronized (needUpdateList){
            needUpdateList.addLast(exchangeData);
        }
    }

    public void addUnionApply(CrossSummerGamesExchangeData exchangeData) {
        List<CrossSummerGamesExchangeData> unionList = unionMap.get(exchangeData.getUnionUid());
        if(unionList == null){
            synchronized (unionMap) {
                unionList = unionMap.get(exchangeData.getUnionUid());
                if(unionList == null){
                    unionList = new LinkedList<>();
                    unionMap.put(exchangeData.getUnionUid(), unionList);
                }
            }
        }
        synchronized (unionList) {
            unionList.add(exchangeData);
        }
    }

    public void removeUnionApply(String unionUid, long applyId) {
        List<CrossSummerGamesExchangeData> unionList = unionMap.get(unionUid);
        if(unionList != null){
            synchronized (unionList) {
                unionList.removeIf(d -> d.getId() == applyId);
            }
        }
    }

    public void addUserApply(CrossSummerGamesExchangeData exchangeData) {
        List<CrossSummerGamesExchangeData> userList = userPublishMap.get(exchangeData.getPUserId());
        if(userList == null){
            synchronized (userPublishMap) {
                userList = userPublishMap.computeIfAbsent(exchangeData.getPUserId(), k -> new LinkedList<>());
            }
        }
        synchronized (userList) {
            userList.add(exchangeData);
        }
    }

    public void removeUserApply(long userId, long applyId) {
        List<CrossSummerGamesExchangeData> userList = userPublishMap.get(userId);
        if(userList != null){
            synchronized (userList) {
                userList.removeIf(d -> d.getId() == applyId);
            }
        }
    }

    public void addUserReceive(CrossSummerGamesExchangeData exchangeData) {
        List<CrossSummerGamesExchangeData> receiveList = userReceiveMap.get(exchangeData.getAUserId());
        if(receiveList == null){
            synchronized (userReceiveMap) {
                receiveList = userReceiveMap.computeIfAbsent(exchangeData.getAUserId(), k -> new LinkedList<>());
            }
        }
        synchronized (receiveList) {
            if(!receiveList.contains(exchangeData)) {
                receiveList.add(exchangeData);
            }
        }
    }

    public void removeUserReceive(long userId, long applyId) {
        List<CrossSummerGamesExchangeData> receiveList = userReceiveMap.get(userId);
        if(receiveList != null){
            synchronized (receiveList) {
                receiveList.removeIf(d -> d.getId() == applyId);
            }
        }
    }

    //只读
    public List<CrossSummerGamesExchangeData> getUserPublishList(long userId){
        return userPublishMap.getOrDefault(userId, Collections.emptyList());
    }

    private CrossSummerGamesExchangeData initExchangeData(long serverId, long playerId, int wantId, int payId) {
        CrossSummerGamesExchangeData exchangeData = new CrossSummerGamesExchangeData();
        exchangeData.setActivityId(getActivityInfo().getActivityId());
        exchangeData.setPServerId(serverId);
        exchangeData.setPUserId(playerId);
        exchangeData.setPGoodsId(payId);
        exchangeData.setWantGoodsId(wantId);
        exchangeData.setStatus(-1);
        exchangeData.setPTime(System.currentTimeMillis());
        exchangeData.setInsertOption();
        exchangeData.setApplyType(eApplyExchangeType.Default.getType());
        return exchangeData;
    }

    public static SummerGamesProto.SummerGamesExchangeInfoTemp.Builder getExchangeBuilder(CrossSummerGamesExchangeData exchangeData) {
        SummerGamesProto.SummerGamesExchangeInfoTemp.Builder builder = SummerGamesProto.SummerGamesExchangeInfoTemp.newBuilder();
        builder.setId(exchangeData.getId());
        builder.setNeedId(exchangeData.getWantGoodsId());
        builder.setProvideId(exchangeData.getPGoodsId());
        builder.setTime(exchangeData.getPTime());
        builder.setAppointUserId(exchangeData.getAUserId());
        builder.setUnionUid(exchangeData.getUnionUid());
        builder.setType(exchangeData.getApplyType());
        builder.setPlayerId(exchangeData.getPUserId());
        builder.setType(exchangeData.getApplyType());
        builder.setTempUserName("");
        builder.setAppointUserServerId(exchangeData.getAServerId());
        builder.setAppointUserServerId(exchangeData.getPServerId());
        builder.setPlayerNickName(exchangeData.getNickName());
        builder.setPlayerServerId(exchangeData.getPServerId());
        return builder;
    }
}
